<?php
// application/models/RoleMapper.php

class Model_RoleMapper
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Model_DbTable_Role');
		}
		return $this->_dbTable;
	}

	public function save(Model_Role $role)
	{
		$data = array(
            'role_name'   => $role->getName(),
		);
		if (null === ($role_id = $role->getId())) {
			unset($data['id']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('role_id = ?' => $role_id));
		}
	}

	public function find($role_id, Model_Role $role)
	{
		$result = $this->getDbTable()->find($role_id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$role->setId($row->role_id)
		->setName($row->role_name);
	}

	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {			
			$entry = new Model_Role();
			$entry->setId($row->role_id)
			->setName($row->role_name);
			$entries[] = $entry;
		}
		return $entries;
	}
}